package com.example.app;

import android.content.Intent;

import com.getcapacitor.JSObject;
import com.getcapacitor.NativePlugin;
import com.getcapacitor.Plugin;
import com.getcapacitor.PluginCall;
import com.getcapacitor.PluginMethod;

import org.json.JSONException;
import org.json.JSONObject;

/**
 *  吉安宝身份认证插件
 */
@NativePlugin(
    requestCodes={OAuthPlugin.OAUTH_LOGIN_REQUEST_CODE}
)
public class OAuthPlugin extends Plugin {

    public static final int OAUTH_LOGIN_REQUEST_CODE = 1;

    /**
     * 认证方法
     * @param call
     */
    @PluginMethod()
    public void authenticate(PluginCall call) {
        String appID = call.getString("appID");
        String url = call.getString("url");
        if(appID == null || url == null){
            call.reject("appID或者url不存在,请正确传递该参数");
        }
        Intent intent = new Intent();
        intent.setAction("com.jit.oauth");
        intent.putExtra("appID", appID);
        intent.putExtra("url", url);
        intent.putExtra("isPortal", false);
        startActivityForResult(call, intent, OAUTH_LOGIN_REQUEST_CODE);
    }

    @Override
    protected void handleOnActivityResult(int requestCode, int resultCode, Intent data) {
        super.handleOnActivityResult(requestCode, resultCode, data);
        // 获取调用插件方法的call
        PluginCall savedCall = getSavedCall();
        if (savedCall == null) {
            return;
        }
        if (requestCode == OAUTH_LOGIN_REQUEST_CODE) {
            if(resultCode == -1){
                if(data != null){
                    System.out.println("172===>"+data.getStringExtra("result"));
                    // 显示返回结果
                    try {
                        JSONObject jsonObject = new JSONObject(data.getStringExtra("result"));
                        if( null != jsonObject ){
                            String stateCode = jsonObject.getString("state");
                            String code = jsonObject.getString("code");
                            String msg = jsonObject.getString("msg");
                            if("0".equals(stateCode)){
                                JSObject ret = new JSObject();
                                ret.put("code", code);
                                savedCall.resolve(ret);
                            }else{
                                savedCall.reject(msg);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }else{
                savedCall.reject("吉安宝调用失败：resultCode为"+resultCode);
            }
        }
    }


}
